package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserBank;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.DialogTypeUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.ValidateUtils;

import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2015/12/30.
 */
public class UpdateBankActivity extends BaseActivity {
    /**
     * 姓名
     */
    TextView textViewUsername;
    /**
     * 身份证号
     */
    TextView textviewIdCard;
    /**
     * 银行卡号编辑框
     */
    EditText editViewBankCard;

    /**
     * 手机号码
     */
    EditText editViewBankPhone;

    /**
     * 选择开户银行编辑框
     */
    EditText editTextBankCategory;
    EditText editTextBankCategoryId;
    /**
     * 选择开户城市编辑框
     */
    EditText editTextBankAddress;
    /**
     * 确认按钮
     */
    Button buttonConfirm;

    UserInfo userInfo;
    UserBank userBank;
    EditText editProviceText;
    EditText editCityText;
    EditText editAreaText;
    EditText editTextCredit;
    private DialogTypeUtils typeUtils;
    Handler checkBindedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<String> data = (Result<String>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            Map<String, String> param = new HashMap<>();
                            String token = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "";
                            String userId = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "";
                            param.put("token", token);
                            param.put("userId", userId);
                            param.put("bankName", editTextBankCategory.getText().toString());
                            param.put("bankId", editTextBankCategoryId.getText().toString());
                            param.put("bankCard", editViewBankCard.getText().toString());
                            param.put("province", editProviceText.getText().toString());
                            param.put("city", editCityText.getText().toString());
                            param.put("area", editAreaText.getText().toString());
                            param.put("creditNo", editTextCredit.getText().toString());

                            //银行卡已经绑定，直接调用保存接口
                            if (data.getData().equals("1")) {
                                //调用修改银行卡信息接口
                                new UpdateBankAsyncTask().execute(param);
                                //银行卡未绑定，跳转到绑定银行卡页面
                            } else {
                                param.put("name", textViewUsername.getText().toString());
                                param.put("idcard", textviewIdCard.getText().toString());
                                Intent bindIntent = new Intent(UpdateBankActivity.this, BindBankConfirmActivity.class);
                                param.put("from", "UpdateBankActivity");
                                param.put("type", "0");
                                String dataJson = gson.toJson(param);
                                bindIntent.putExtra("dataJson", dataJson);
                                startActivity(bindIntent);
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
            closeWaitDialog();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_bank_card);
        init();
        initView();
        typeUtils=new DialogTypeUtils(this);
    }

    private void initView() {
         textViewUsername=(TextView)findViewById(R.id.textView_username);
         textviewIdCard=(TextView)findViewById(R.id.textview_id_card);
         editViewBankCard=(EditText)findViewById(R.id.editView_bank_card);
         editViewBankPhone=(EditText)findViewById(R.id.editView_bank_phone);
         editTextBankCategory=(EditText)findViewById(R.id.editText_BankCategory);
         editTextBankCategoryId=(EditText)findViewById(R.id.editText_BankCategory_id);
         editTextBankAddress=(EditText)findViewById(R.id.editText_BankAddress);
         buttonConfirm=(Button)findViewById(R.id.button_confirm);
         editProviceText=(EditText)findViewById(R.id.update_bank_provice_text);
         editCityText=(EditText)findViewById(R.id.update_bank_city_text);
         editAreaText=(EditText)findViewById(R.id.update_bank_area_text);
         editTextCredit=(EditText)findViewById(R.id.editText_credit);
        Intent intent = this.getIntent();
        try{
            userInfo = (UserInfo) intent.getSerializableExtra("userInfo");
            userBank = (UserBank) intent.getSerializableExtra("userBank");

            textViewUsername.setText(userInfo.getName());
            textviewIdCard.setText(userInfo.getIdcard());

            editViewBankCard.setText(userBank.getBankCard());
            editTextBankCategory.setText(userBank.getDeposit());
            editTextBankCategoryId.setText(userBank.getBankId().toString());
            editProviceText.setText(userBank.getProvince());
            editCityText.setText(userBank.getCity());
            editAreaText.setText(userBank.getArea());
            editViewBankPhone.setText(userBank.getPhoneNo());
            editTextCredit.setText(userBank.getCreditNo());

            String city = "";
            if (userBank.getProvince().equals(userBank.getCity())) {
                city = userBank.getProvince() + userBank.getArea();
            } else {
                city = userBank.getProvince() + userBank.getCity() + userBank.getArea();
            }
            editTextBankAddress.setText(city);
        }catch (Exception e){

        }




        ButtonListener listener = new ButtonListener();

        editTextBankCategory.setOnClickListener(listener);
        editTextBankAddress.setOnClickListener(listener);
        buttonConfirm.setOnClickListener(listener);

    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(R.id.editText_BankCategory==v.getId()) {
                    alertBankSelectDialog(editTextBankCategory, editTextBankCategoryId);
            }
            else if(R.id.editText_BankAddress==v.getId()) {
                    if (typeUtils != null) {
                        if ((typeUtils.getOptions1Items() != null && (typeUtils.getOptions1Items().size() != 0)) &&
                                (typeUtils.getOptions2Items() != null && (typeUtils.getOptions2Items().size() != 0)) &&
                                (typeUtils.getOptions3Items() != null && (typeUtils.getOptions3Items().size() != 0))) {
                            typeUtils.showPickerView(editTextBankAddress, editProviceText, editCityText, editAreaText);
                        } else {
                            typeUtils.initJsonData(UpdateBankActivity.this);
                            typeUtils.showPickerView(editTextBankAddress, editProviceText, editCityText, editAreaText);
                        }
                    }
            }
            else if(R.id.button_confirm==v.getId()){
                    if (StringUtils.isBlank(editViewBankCard.getText().toString())
                            || StringUtils.isBlank(editTextBankCategory.getText().toString())
                            || StringUtils.isBlank(editProviceText.getText().toString())
                            || StringUtils.isBlank(editCityText.getText().toString())
                            || StringUtils.isBlank(editAreaText.getText().toString())) {
                        showShortToast1("银行卡信息没有填完整");
                        return;
                    }

                    if (!ValidateUtils.isMobile(editViewBankPhone.getText().toString())) {
                        showShortToast1("手机号填写不正确");
                        return;
                    } else {
                        Map<String, String> param = new HashMap<>();
                        String token = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "";
                        String userId = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "";
                        param.put("token", token);
                        param.put("userId", userId);
                        param.put("bankName", editTextBankCategory.getText().toString());
                        param.put("bankId", editTextBankCategoryId.getText().toString());
                        param.put("bankCard", editViewBankCard.getText().toString());
                        param.put("province", editProviceText.getText().toString());
                        param.put("city", editCityText.getText().toString());
                        param.put("area", editAreaText.getText().toString());
                        param.put("phoneNo", editViewBankPhone.getText().toString());
                        param.put("creditNo", editTextCredit.getText().toString());
                        new UpdateBankAsyncTask().execute(param);
                    }
            }
        }
    }

    private class UpdateBankAsyncTask extends AsyncTask<Map, Void, Result<UserBank>> {
        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }

        @Override
        protected Result<UserBank> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/changeBankCard", params[0], UpdateBankActivity.this);
            Result<UserBank> resultObject = Result.fromJson(result, UserBank.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(Result<UserBank> result) {
            if(result!=null) {
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    showShortToast1(result.getMsg());
                    UserBank userBank = result.getData();
//                result
                    //更新数据库
                    UserBank.deleteAll(UserBank.class);
                    userBank.save();
                    UpdateBankActivity.this.finish();
                } else {
                    showShortToast1(result.getMsg());
                }
            }
            else{
                showShortToast1("连接超时");
            }
            closeWaitDialog();
        }
    }
}
